package org.fas.taskQueue
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	
	import org.fas.utils.FuArray;
	
	public class FTaskQueue extends EventDispatcher
	{
		private var taskArray:FTaskArray = new FTaskArray();
		private var successDictionary:Dictionary = new Dictionary();
		private var faultDictionary:Dictionary = new Dictionary();
		private var execingTask:IFTask;
		private var er_autoStart:Boolean;
		private var startTimer:int;
		public function FTaskQueue(_autoStart:Boolean)
		{
			super();
			this.autoStart = _autoStart;
		}

		public function get autoStart():Boolean
		{
			return er_autoStart;
		}

		public function set autoStart(v:Boolean):void
		{
			er_autoStart = v;
		}

		public function get isExecing():Boolean{
			return Boolean(this.execingTask!=null);
		}
		public function addTask(_task:IFTask,_successCallback:Function=null,_faultCallback:Function=null):void{
			this.taskArray.push(_task);
			this.successDictionary[_task] = _successCallback;
			this.faultDictionary[_task] = _faultCallback;
			if(this.autoStart && !this.isExecing){
				this.start();
			}
		}
		public function start():void{
			if(this.taskArray.length>0){
				var _task:IFTask = this.taskArray.c(0);
				_task.success = this.successCallback;
				_task.fault = this.faultCallback;
				this.execingTask = _task;
				this.logBegin();
				_task.execute();
			}
		}
		private function logBegin():void{
			trace('--- F-Task Execut: [',this.execingTask.taskName,']');
			this.startTimer = flash.utils.getTimer();
		}
		private function logEnd():void{
			trace('--- F-Task Success: [',this.execingTask.taskName,'] Used Time:',(flash.utils.getTimer()-this.startTimer)/1000,'Seconds');
		}
		private function successCallback(...args):void{
			this.logEnd();
			var _callback:Function = this.successDictionary[execingTask] as Function;
			if(_callback!=null){
				_callback(args);
			}
			this.startNextTask();
		}
		private function faultCallback(...args):void{
			var _callback:Function = this.faultDictionary[execingTask] as Function;
			if(_callback!=null){
				_callback(args);
			}
			this.startNextTask();
		}
		private function startNextTask():void{
			var _task:IFTask = this.execingTask;
			this.execingTask = null;
			this.removeTask(_task);
			this.start();
		}
		public function removeTask(_task:IFTask):void{
			if(this.execingTask!=_task){
				_task.success = null;
				_task.fault = null;
				FuArray.del(this.taskArray,_task);
				delete this.successDictionary[_task];
				delete this.faultDictionary[_task];
			}
		}
		public function stop():void{
			
		}
		public function resume():void{
			
		}
		public function removeAll():void{
			
		}
	}
}
